package ifeishu

import (
	"errors"
	"github.com/emirpasic/gods/lists"
	"strings"
	icollection "walis-vue3/server/common/kits/collections"
	ihttp "walis-vue3/server/common/kits/http"
	ijson "walis-vue3/server/common/kits/json"
)

// TextMessage 普通文本消息
type FeiShuMessage struct {
	Receiver    string      `json:"receive_id"`
	Content     interface{} `json:"content"`
	MessageType string      `json:"msg_type"`
}

func BuildNormalText(title, message string) (FeiShuMessage, error) {
	// Message 封装
	txt := map[string]string{}
	txt["text"] = title + "\n" + message
	content, err := ijson.ToJsonString(txt)
	if err != nil {
		return FeiShuMessage{}, errors.New(err.Error())
	}
	msg := FeiShuMessage{Content: content, MessageType: "text"}
	_, jsonErr := ijson.ToJsonString(msg)
	if jsonErr != nil {
		return FeiShuMessage{}, jsonErr
	}
	return msg, nil
}

// RichMessage 富文本消息
type RichMessage struct {
	Payload RichLanguage `json:"post"`
}
type RichLanguage struct {
	Cn RichContent `json:"zh_cn"`
}
type RichContent struct {
	Title   string     `json:"title"`
	Content lists.List `json:"content"`
}
type RichRow struct {
	Tag  string `json:"tag"`
	Text string `json:"text"`
}

func BuildRichText(title string, values []string) (FeiShuMessage, error) {
	// Message 封装
	contentList := icollection.NewArrayList()
	for i := 0; i < len(values); i++ {
		msg := values[i]
		row := []RichRow{RichRow{Tag: "text", Text: msg}}
		contentList.Add(row)
	}
	content := RichContent{Title: title, Content: contentList}
	cn := RichLanguage{Cn: content}
	msg := RichMessage{Payload: cn}
	jsonValue, jsonErr := ijson.ToJsonString(msg)
	if jsonErr != nil {
		return FeiShuMessage{}, jsonErr
	}

	feiShu := FeiShuMessage{MessageType: "post", Content: jsonValue}
	return feiShu, nil
}

// SendRichText 发送富文本消息
func SendRichText(url string, title string, rows []string) {
	message, err := BuildRichText(title, rows)
	if err != nil {
		println(err.Error())
	}
	Send2FeiShu(url, message)
}

// Send2FeiShu 发送 WebHook 消息
// 文件传输助手WebHook: https://open.feishu.cn/open-apis/bot/v2/hook/ae97d2df-4e6f-4035-99f0-717630da3a67
func Send2FeiShu(url string, message interface{}) error {
	// 消息体格式化
	jsonValue, jsonErr := ijson.ToJsonString(message)
	if jsonErr != nil {
		return jsonErr
	}
	println(jsonValue)

	// Http 请求封装
	headers := map[string]string{}
	response, httpErr := ihttp.Post(url, headers, strings.NewReader(jsonValue))
	if httpErr != nil {
		return httpErr
	}
	println(response.GetStatusCode())
	println(response.GetContent())
	return nil
}
